package com.autodesk.akn.emr.util;



import com.autodesk.akn.emr.util.opendatafoundation.data.FileFormatInfo;
import com.autodesk.akn.emr.util.opendatafoundation.data.spss.SPSSFile;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.StringWriter;
import java.util.logging.Logger;


public class SPSSUtil {
	/**
	 * Method to export a SPSS file to a CSV
	 * @param inputFile
	 * @param outputFile
     * @param headersOnly - indicate if only need to export the headers or the entire data
	 * @return the exportation time
	 */
    private final static Logger LOGGER = Logger.getLogger(SPSSUtil.class.getName());
	public long export(File inputFile, File outputFile, boolean headersOnly){
		try {
			//The input SPSS file
			SPSSFile file = new SPSSFile(inputFile);
			//Load the Metadata
			file.loadMetadata();
	        //Create a new FileFormatInfo to export with CSV Format 
	        FileFormatInfo ffi = new FileFormatInfo(FileFormatInfo.Format.ASCII);
	        ffi.namesOnFirstLine = true;
            ffi.asciiDelimiter = '|';
	        ffi.asciiFormat = FileFormatInfo.ASCIIFormat.DELIMITED;
	        //Perform the exportation
            LOGGER.info("EXPORTING DATA");
	        long exportationTime = file.exportData(outputFile, ffi, headersOnly);
            LOGGER.info("DATA EXPORTED - TIME:"+exportationTime+"ms");
	        return exportationTime;
		} catch (Exception e){
			throw new RuntimeException(e.getMessage());
		}
	}
	
	/**
	 * Method to obtain the XML metadata of a SPSS file
	 * @param input
	 * @return a String with the XML metadata
	 */
	public String getMetadataXML(String input){
		try {
			//The input SPSS file
			File f = new File(input);
			SPSSFile file = new SPSSFile(f);
			//Load the metadata
			file.loadMetadata();
			//Transform and return the XML info
			TransformerFactory transFactory = TransformerFactory.newInstance();
	        StringWriter writer = new StringWriter();
	        transFactory.newTransformer().transform(new DOMSource(file.getDDI2(new FileFormatInfo())),new StreamResult(writer));
	        String result = writer.getBuffer().toString();
	        return result;
		} catch(Exception e){
			throw new RuntimeException(e.getMessage());
		}
	}
}
